<template>
  <div class="content_index">
    <div class="ci_header">
      <div class="ci_left sec-title">
        <el-icon
          style="vertical-align: middle; display: unset; cursor: pointer"
          @click="backList()"
          ><Back
        /></el-icon>
        <span>创建VP</span>
      </div>
    </div>
    <div class="ci_content" style="margin: 12px 16px">
      <el-form
        :model="form"
        ref="cptFormRef"
        :rules="cptFormRefRules"
        label-width="120px"
        style="width: 100%"
      >
        <el-form-item label="名称：" prop="name">
          <el-input v-model.trim="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="凭证：" prop="credentialId">
          <el-select
            @change="changeCredentialId(form.credentialId)"
            v-model="form.credentialId"
            placeholder="请选择凭证"
            style="width: 100%"
          >
            <el-option
              v-for="(item, index) in voucher.voucherList"
              :key="index"
              :label="item.credentialName"
              :value="item.credentialId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="属性列表：" prop="claims">
          <div
            v-for="(item, index) of voucher.attributeList"
            :key="index"
            class="center_start"
            style="width: 100%"
          >
            <div>
              <span>{{ index }}：</span>
              <span>{{ item }}</span>
            </div>
            <el-checkbox
              :model-value="true"
              disabled
              size="large"
              style="margin-left: 10%"
            />
          </div>
        </el-form-item>
        <el-form-item label="附加信息：" prop="additionalInfo">
          <el-row
            v-for="(item, index) in form.additionalInfo"
            :key="index + 1"
            style="width: 100%; border: 1px soild #dcdfe6"
          >
            <el-col :span="11">
              <el-form-item
                label="名称"
                :prop="'additionalInfo.' + index + '.name'"
                :rules="{
                  max: 50,
                  required: true,
                  message: '请输入名称，50字符以内',
                  trigger: 'blur',
                }"
              >
                <el-input
                  type="text"
                  v-model.trim="item.name"
                  placeholder="请输入名称"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item
                label="值"
                :prop="'additionalInfo.' + index + '.value'"
                :rules="{
                  max: 50,
                  required: true,
                  message: '限制50位字符以内',
                  trigger: 'blur',
                }"
              >
                <el-input
                  type="text"
                  v-model.trim="item.value"
                  placeholder="请输入值"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="1" v-if="index !== 0">
              <el-icon class="delete_icon" @click="removeDomain(index)"
                ><Remove
              /></el-icon>
            </el-col>
            <el-col :span="1">
              <el-icon class="add_icon" @click="addDomain"
                ><CirclePlus
              /></el-icon>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" :loading="isLoading"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script setup>
import { reactive, ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { CreateVP, credentialListApi, claimsListApi } from "@/api/VP";
import { ElMessage } from "element-plus";
import { nameValidator } from "@/utils/validate";
const router = useRouter();
const backList = () => {
  router.go(-1);
};
const isLoading = ref(false);
const cptFormRef = ref("form");
const voucher = reactive({
  voucherList: [],
  attributeList: {},
});
const form = reactive({
  name: "",
  credentialId: "",
  claims: "",
  additionalInfo: [
    {
      name: "",
      value: "",
    },
  ],
  domain: "localhost",
});
/** VP名称校验 */
const validateCPTName = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("VP名称不能为空"));
  } else {
    // 校验昵称
    if (!nameValidator(value)) {
      rule.message =
        "2-50位字符，不能以特殊字符及数字开头，只可包含特殊字符中的'.','_'或'-'";
      callback(new Error());
    } else {
      callback();
      // 注意，这个空的callback非常重要，没有它作为结束，整个校验会出问题
    }
  }
};
const name = (name) => {
  let flse = ref(false);
  if (form.additionalInfo.length < 2) {
    return false;
  }
  form.additionalInfo.forEach((item) => {
    if (item.name === name) {
      flse.value = true;
    } else {
      flse.value = false;
    }
  });
  return flse.value;
};
/** 表单校验规则 */
const cptFormRefRules = {
  name: [
    {
      required: true,
      validator: validateCPTName,
      message:
        "2-50位字符，不能以特殊字符及数字开头，只可包含特殊字符中的'.','_'或'-'",
      trigger: "blur",
    },
    {
      max: 50,
      min: 2,
      message:
        "2-50位字符，不能以特殊字符及数字开头，只可包含特殊字符中的'.','_'或'-'",
      trigger: "blur",
    },
  ],
  credentialId: [
    {
      required: true,
      message: "请选择凭证",
      trigger: "blur",
    },
  ],
};
const onSubmit = () => {
  const timeStamp = new Date().getTime();

  cptFormRef.value?.validate(async (valid) => {
    if (valid) {
      isLoading.value = true;
      let attributeObj = {};
      form.additionalInfo.forEach((item) => {
        attributeObj[item.name] = item.value;
      });
      let parmars = {
        ...form,
        additionalInfo: JSON.stringify(attributeObj),
        claims: JSON.stringify(voucher.attributeList),
        challenge: timeStamp + "",
      };
      CreateVP(parmars)
        .then((res) => {
          if (res.success && res.data) {
            router.push({ path: "/VPManagement/VPList" });
            isLoading.value = false;
            ElMessage.success(res.msg || "VP创建成功!");
          } else {
            ElMessage.error(res.msg || "VP创建失败!");
            isLoading.value = false;
          }
        })
        .catch((err) => {
          ElMessage.error(err.msg || "VP创建失败!");
          isLoading.value = false;
        });
    } else {
      return false;
    }
  });
};
const addDomain = () => {
  if (form.additionalInfo.length > 9) {
    ElMessage.error("文件最多添加10条！");
    return false;
  }
  form.additionalInfo.push({
    name: "",
    value: "",
  });
};
const removeDomain = (index) => {
  if (index !== 0) {
    form.additionalInfo.splice(index, 1);
  }
};
const voucherList = () => {
  credentialListApi()
    .then((res) => {
      if (res.success) {
        voucher.voucherList = res.data || [];
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch((err) => {
      ElMessage.error(err.msg);
    });
};
const changeCredentialId = (credentialId) => {
  voucher.attributeList = [];
  attributeList(credentialId);
};
// 属性列表
const attributeList = (credentialId) => {
  claimsListApi(credentialId)
    .then((res) => {
      if (res.success && res.data) {
        voucher.attributeList = JSON.parse(res.data.claims);
      } else {
        ElMessage.error(res.msg);
        voucher.attributeList = {};
      }
    })
    .catch((err) => {
      ElMessage.error(err.msg);
      voucher.attributeList = {};
    });
};
onMounted(() => {
  voucherList();
});
</script>

<style lang="scss" scoped>
@import "../../assets/css/cindex.scss";
:deep .el-upload-list--picture-card .el-upload-list__item-actions span + span {
  margin-left: 0.5em;
}
.add_icon {
  font-size: 18px;
  // margin-left: 10px;
  cursor: pointer;
  height: 100%;
}
.delete_icon {
  font-size: 18px;
  margin-left: 10px;
  cursor: pointer;
  height: 100%;
}
.box {
  display: flex;
  .left_txContent {
    // width: 200px;
    width: 50%;
    padding: 20px;
    // height: 200px;
    // background: pink;
    border-radius: 8px;
    border: 1px solid #d6e9c6;
    word-break: break-word;
    margin-right: 10px;
  }
  .rigth_txContent {
    width: 50%;
    padding: 20px;

    // width: 200px;
    // height: 200px;
    // background: red;
    border-radius: 8px;
    border: 1px solid #d6e9c6;
    word-break: break-word;
  }
}
.file_cn {
  // width: 130px;
  width: 100%;
  font-size: 14px;
  //   text-align: right;
  // margin-left: 70px;
  margin-bottom: 5px;
  padding: 10px;
  border-radius: 4px;
  border: 1px dashed #a6a6a6;
  div {
    margin-bottom: 15px;
  }
}
.Sign_content {
  display: flex;
  font-size: 14px;
  .Sign_content_key {
    display: inline-flex;
    justify-content: flex-end;
    align-items: flex-start;
    flex: 0 0 auto;
    height: 32px;
    line-height: 32px;
    padding: 0 12px 0 0;
    box-sizing: border-box;
    width: 90px;
  }
  .Sign_content_data {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    flex: 1;
    line-height: 32px;
    position: relative;
    min-width: 0;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }
}

.red {
  color: red;
}
.green {
  color: green;
}
.el-form-item {
  width: 100%;
  margin-bottom: 20px;
}
.el-form-item .el-row {
  border: 1px soild #dcdfe6 !important;

  //   box-sizing: unset;
}
.wordWrap {
  word-break: break-word;
}
:deep .el-descriptions .el-descriptions__label {
  display: inline-block;
  width: 100px;
  text-align: right;
}
.add_icon {
  font-size: 18px;
  margin-left: 10px;
  cursor: pointer;
  height: 100%;
}
.delete_icon {
  font-size: 18px;
  margin-left: 10px;
  cursor: pointer;
  margin-bottom: 20px;
  height: 100%;
}
</style>
